package com.wyy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wyy.beans.Car;
import com.wyy.dao.CarDao;
import com.wyy.service.CarService;
import com.wyy.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CarServiceImpl extends ServiceImpl<CarDao, Car> implements CarService {

    @Autowired
    private CarDao carDao;

    @Override
    public Result<Car> addCar(Car car) {
        QueryWrapper<Car> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(true, "license_plate_no", car.getLicensePlateNo());
        Car newCar = this.getOne(queryWrapper);

        if (newCar != null) {
            return new Result<>(Result.ResultStatus.Failed.code,  "fail");
        }

        int aff = carDao.insert(car);
        return aff == 0 ? new Result<>(Result.ResultStatus.Failed.code,  "fail")
                : new Result<>(Result.ResultStatus.SUCCESS.code, "success");
    }

    @Override
    public Result<Car> deleteCar(String licensePlateNo) {
        QueryWrapper<Car> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(true, "license_plate_no", licensePlateNo);
        boolean aff = this.remove(queryWrapper);
        return !aff ? new Result<>(Result.ResultStatus.Failed.code,  "fail")
                : new Result<>(Result.ResultStatus.SUCCESS.code, "success");
    }


    @Override
    public Result<Car> getCar(String licensePlateNo) {
        QueryWrapper<Car> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(true, "license_plate_no", licensePlateNo);
        Car car = carDao.selectOne(queryWrapper);
        return car == null ? new Result<>(Result.ResultStatus.Failed.code,  "fail")
                : new Result<>(Result.ResultStatus.SUCCESS.code, "success", car);
    }

    @Override
    public Result<List<Car>> getCars() {
        List<Car> cars = carDao.findAllCars();
        return cars.size() == 0 ? new Result<>(Result.ResultStatus.Failed.code,  "fail")
                : new Result<>(Result.ResultStatus.SUCCESS.code, "success", cars);
    }

    @Override
    public Result<List<Car>> getCarsByUserTelephone(String telephoneNumber) {
        QueryWrapper<Car> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(true, "telephone_number", telephoneNumber);
        List<Car> cars = carDao.selectList(queryWrapper);
        return cars.size() == 0 ? new Result<>(Result.ResultStatus.Failed.code,  "fail")
                : new Result<>(Result.ResultStatus.SUCCESS.code, "success", cars);
    }
}
